package nb.photoviewer.slideshow;

import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Cursor;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.ScrollPane;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.*;
import javafx.stage.Stage;
import javafx.stage.WindowEvent;
import nb.photoviewer.ImageEditor.EditorController;
import nb.photoviewer.MainApplication;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;

public class SlideController implements Initializable{

    @FXML
    private ImageView imageView;   //获取对fxml中的主视图imageview

    @FXML
    private BorderPane slideShowPane;    //主borderpane
    @FXML
    private HBox imageHBox; //幻灯片跑马灯图片区域
    @FXML
    private ScrollPane imagescrollpane;  //跑马灯scrollerpane

    //scrollerpane实现左右拖动
    private double xOffset = 0;
    private double yOffset = 0;

    @FXML
    private Button amplifyButton;     //放大按钮
    @FXML
    private Button reduceButton;      //缩小按钮
    @FXML
    private Button nextButton;    //下一张按钮
    @FXML
    private Button previousButton;   //上一张按钮
    @FXML
    private Button startButton;    //自动播放按钮
    @FXML
    private Button stopButton;    //停止播放按钮
    @FXML
    private Button ClockwiseButton;   //顺时针旋转
    @FXML
    private Button CounterClockwiseButton;  //逆时针旋转
    @FXML
    private Button editButton;        //编辑图片按钮
    @FXML
    private Button deletButton;
    @FXML
    private Label messageLabel;//播放图片的名称与大小
    @FXML
    private Label firstLabel;   //第一张图片切换上一张提示
    @FXML
    private Label lastLabel;    //最后一张图片切换下一张提示


    SlideShowManager slideShowManager;     //管理图片数据

    private List<File> imageFiles = new ArrayList<>();   // 声明一个变量来保存文件数组————到时候要传给SlideShowManager的
    private int currentIndex=0;
    @Override
    //初始化所有控件的数据，
    public void initialize(URL url, ResourceBundle resourceBundle) {
        //给按钮加图标
        // 创建图标
        FileInputStream input1=null,input2= null,input3=null,input4=null,input5=null,input6=null;
        FileInputStream input7=null,input8=null ,input9=null,input10=null;
        try {
            input1= new FileInputStream("src/main/resources/nb/photoviewer/img/左箭头.png");
            input2 = new FileInputStream("src/main/resources/nb/photoviewer/img/右箭头.png");
            input3= new FileInputStream("src/main/resources/nb/photoviewer/img/放大按钮.png");
            input4 = new FileInputStream("src/main/resources/nb/photoviewer/img/缩小按钮.png");
            input5= new FileInputStream("src/main/resources/nb/photoviewer/img/逆时针旋转.png");
            input6 = new FileInputStream("src/main/resources/nb/photoviewer/img/顺时针旋转.png");
            input7= new FileInputStream("src/main/resources/nb/photoviewer/img/开始播放.png");
            input8 = new FileInputStream("src/main/resources/nb/photoviewer/img/停止播放.png");
            input9 = new FileInputStream("src/main/resources/nb/photoviewer/img/编辑图片.png");
            input10 = new FileInputStream("src/main/resources/nb/photoviewer/img/删除图片.png");
            initializeButton(input1,previousButton);
            initializeButton(input2,nextButton);
            initializeButton(input3,amplifyButton);
            initializeButton(input4,reduceButton);
            initializeButton(input5,CounterClockwiseButton);
            initializeButton(input6,ClockwiseButton);
            initializeButton(input7,startButton);
            initializeButton(input8,stopButton);
            initializeButton(input9,editButton);
            initializeButton(input10,deletButton);
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        }

        // 添加鼠标悬停事件监听器，当鼠标停留在imageview上时切换为手形
        imageView.setOnMouseEntered(event -> {
            imageView.setCursor(Cursor.HAND); // 鼠标悬停时改变鼠标图标为手型
        });

        // 添加滚轮事件监听器
        imageView.setOnScroll(event -> {
            double deltaY = event.getDeltaY(); // 获取滚轮滚动的垂直距离
            // 根据滚动方向调整图片大小
            if (deltaY < 0) {
                reduceImage();
            } else {
                amplifyImage();
            }
            event.consume(); // 防止滚动事件继续传播
        });

        imageView.setOnMouseExited(event -> {
            imageView.setCursor(Cursor.DEFAULT); // 鼠标离开时恢复默认图标
        });
        //设置scrollerpane拖动还有隐藏滑轮
        initializeScrollerPane(imagescrollpane);

        System.out.println("SlideController   initialize 先");
        //创建一个SlideSlowStage对象，管理幻灯片
        slideShowManager =new SlideShowManager(imageView,imageHBox,messageLabel,firstLabel,lastLabel,imagescrollpane);
        System.out.println("SlideController  initialize 后");
        //事实证明，先执行initialize才会执行其他的
    }

    // 添加一个方法来接收文件数组，注意，要把主窗口的列表传到SlideShowManager里面，不能通过构造方法来传，因为setImageFiles比initialize晚运行
    public void setImageFiles(List<File> Files,int currentIndex) {
        this.imageFiles = Files;
        this.currentIndex=currentIndex;

        for(int i=0;i<imageFiles.size();i++){
            System.out.println("SlideController setImageFiles方法   "+imageFiles.get(i).getName());   //判断一下有没有传过来
        }
        //确实已经传过来了，存储在imageFiles中
        slideShowManager.SetImageFiles(Files,currentIndex);
    }

    private void initializeButton(FileInputStream input,Button button){
        ImageView icon=new ImageView(new Image(input));
        icon.setFitWidth(35);
        icon.setFitHeight(35);
        button.setGraphic(icon);
    }
    private void initializeScrollerPane(ScrollPane scrollpane){
        scrollpane.setCenterShape(true);
        // 设置水平滚动条始终显示，垂直滚动条不显示
        scrollpane.setHbarPolicy(ScrollPane.ScrollBarPolicy.NEVER);
        scrollpane.setVbarPolicy(ScrollPane.ScrollBarPolicy.NEVER);
        // 鼠标按下记录偏移量
        scrollpane.setOnMousePressed(event -> {
            xOffset = event.getSceneX();
            yOffset = event.getSceneY();
            scrollpane.setPannable(true);
        });
        // 鼠标拖动时更新滚动位置
        scrollpane.setOnMouseDragged(event -> {
            scrollpane.setHvalue(scrollpane.getHvalue() - (event.getSceneX() - xOffset) / scrollpane.getWidth());
            scrollpane.setVvalue(scrollpane.getVvalue() - (event.getSceneY() - yOffset) / scrollpane.getHeight());
        });
        // 鼠标释放停止拖动
        scrollpane.setOnMouseReleased(event -> {
            scrollpane.setPannable(false);
        });
    }

    @FXML
    private void previousImageButtonClicked(){ //上一张图片按钮
        this.slideShowManager.PreviousImage();
    }

    @FXML
    private void nextImageButtonClicked(){    //下一张图片按钮
         this.slideShowManager.NextImage();
    }

    @FXML
    private void StartAutoPlayButton(){    //自动播放按钮响应事件
        this.slideShowManager.StartAutoPlay();
        startButton.setDisable(true);
    }

    @FXML
    private void StopAutoPlayButton(){     //停止播放按钮响应事件
        this.slideShowManager.StopAutoPlay();
        startButton.setDisable(false);
    }


    @FXML
    private void amplifyImage() {    //放大功能
        imageView.setScaleX(imageView.getScaleX() * 1.2);
        imageView.setScaleY(imageView.getScaleY() * 1.2);
    }
    @FXML
    private void reduceImage() {   //缩小功能
        imageView.setScaleX(imageView.getScaleX() / 1.2);
        imageView.setScaleY(imageView.getScaleY() / 1.2);
    }

    @FXML
    private void rotateClockwise(){
        // 将图片顺时针旋转90度
        imageView.setRotate(imageView.getRotate() + 90);
    }
    @FXML
    private void rotateCounterClockwiseButton(){
        // 将图片逆时针旋转90度
        imageView.setRotate(imageView.getRotate() - 90);
    };

    @FXML
    void removeImage(){
        slideShowManager.removeImageFromView();
    }

    //图片编辑部分
    @FXML
    void openImageEditorStage() throws Exception {
        System.out.println("打开编辑窗口函数成功");
        //加载幻灯片界面的FXML文件
        FXMLLoader loader =new FXMLLoader(getClass().getResource("/nb/photoviewer/ImageEditorStage.fxml"));
        System.out.println("加载fxml文件成功");
        System.out.println( getClass().getResource("/nb/photoviewer/ImageEditorStage.fxml"));//打印出来是null
        try {
            Parent EditorImageRoot = loader.load();//为什么这里又出错了
            System.out.println("Parent");
            //获取幻灯片控制器并初始化图片文件
            EditorController editorController = loader.getController();
            System.out.println(editorController);   //为什么会是null呢

            System.out.println("1");
            System.out.println("回到SlideShowController,开始传image");
            System.out.println(imageFiles.get(slideShowManager.getImageFilesIndex()).getName());
            //把当前播放的图片传到EditorController
            editorController.setEditImage(imageFiles.get(slideShowManager.getImageFilesIndex()));

            //创建和显示幻灯片界面的窗口
            Scene scene = new Scene(EditorImageRoot);
            Stage ImageEditorStage = new Stage();
            ImageEditorStage.setScene(scene);
            ImageEditorStage.setTitle("编辑图片");

            // 设置图标
            Image imageEditorIcon = new Image("file:src/main/resources/nb/photoviewer/img/编辑.png");
            ImageEditorStage.getIcons().add(imageEditorIcon);

            //创建了一个新的场景，并将加载的FXML文件的根节点设置为该场景的根节点。
            // 设置Stage的最小宽度和高度
            ImageEditorStage.setMinWidth(900);
            ImageEditorStage.setMinHeight(620);
            ImageEditorStage.show();
            // 当新窗口关闭时执行的操作
            ImageEditorStage.setOnCloseRequest(new EventHandler<WindowEvent>() {
                @Override
                public void handle(WindowEvent event) {
                    // 重新启用按钮
                    editButton.setDisable(false);
                }
            });
            // 禁用按钮，避免多次点击
            editButton.setDisable(true);
        }catch(IOException e) {
            e.printStackTrace();//处理异常
        }
    }
}
